﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//
using System.Text.RegularExpressions;

// GetTPB, Copyright Mirosław M. Mączka.  All Rights Reserved. This code released under the terms of the Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
namespace GetTpb
{
    public class ReadAllPages
    {

        static public bool Do(HashSet<TpbItem> hs, TpbSource ss, out int nPages, out string ErrorMessage)
        {
            ErrorMessage = "";
            string webPageBody = "";
            ParsePage pp = new ParsePage();
            string nextPage ="";
            nPages=0;
            //
            if ("" != ss.Selection.Trim())
            {
                try
                {
                    ParsePage.rSelection = new Regex(ss.Selection, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                }
                catch
                {
                    ParsePage.rSelection = null;
                }
            }
            //
            if (!ReadWebPage.Do(ss.webPage, out webPageBody, out ErrorMessage))
            {
                return false;
            }
            //
            //
            pp.Do(webPageBody, hs, ss, out nextPage);
            if ("" == nextPage)
            {
                return true;
            }
            //
            do
            {
                nPages++;
                nextPage = Utils.GetNextPage(ss.webPage, nextPage);
                if ("" == nextPage) break;
                if (!ReadWebPage.Do(nextPage, out webPageBody, out ErrorMessage))
                {
                    break;
                }
                //
                pp.Do(webPageBody, hs, ss, out nextPage);
                //
                if(0 != ss.maxCount)
                {
                    if(hs.Count > ss.maxCount)
                    {
                        break;
                    }
                }
                //
            } while (""!=nextPage);
            //
            return true;
            //
        }
            //
        //
    }//class
}//namespace
